﻿using System;
using System.Windows.Forms;
using Common;
using CSGame.DispatcherService;
using System.ServiceModel;

namespace CSGame
{
	public delegate void ReceivedMessageHandler(string msg);
	public delegate void InvitedHandler(string userName, string invitedUserName);
	public delegate void StartGame(GameInfo gameInfo);

    static class Program
    {
		static frmMain _main;
        /// <summary>
        /// Главная точка входа для приложения.
        /// </summary>
        [STAThread]
        static void Main()
        {
			try
			{
				Application.EnableVisualStyles();
				Application.SetCompatibleTextRenderingDefault(false);
				_main = new frmMain();
				DispatcherCallbackHandler handler = new DispatcherCallbackHandler(_main);
				DispatcherClient dispatcher = new DispatcherClient(new System.ServiceModel.InstanceContext(handler));
				dispatcher.Open();
				Application.Run(new frmAuthorization(dispatcher));
			}
			catch (Exception ex)
			{
				MessageBox.Show(Common.Resources.ConnectionExceptionMsg, Resources.ErrorMsgCaption, MessageBoxButtons.OK,
					MessageBoxIcon.Error);
			}
        }

		public static frmMain MainForm
		{
			get { return _main; }
		}
    }

	[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
	public partial class DispatcherCallbackHandler : IDispatcherCallback
	{
		frmMain _main;

		public DispatcherCallbackHandler(frmMain main)
		{
			this._main = main;
		}

		public void ReceivedMessage(string msg)
		{
			_main.Invoke(_main._receivedMessageHanlder, new object[] { msg });
		}

		public void UserJoined(string userName)
		{
			_main.Invoke(_main._userJoinedHandler, new object[] { userName });
		}

		public void UserLeft(string userName)
		{
			_main.Invoke(_main._userLeftHandler, new object[] { userName });
		}

		public void Invited(string userName, string invitedUserName)
		{
			_main.Invoke(_main._invitedHandler, new object[] { userName, invitedUserName });
		}

		public void InviteAccepted(GameInfo gf)
		{
			_main.Invoke(_main._startGame, new object[] { gf });
		}
	}
}